<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/10/24
 * Time: 下午2:00
 */

namespace Modules\Api\Controllers;

use App\Models\Configure;
use App\Models\OilCard;
use App\Models\User;
use App\Models\UserCoupon;
//use App\Sms;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Modules\Token\Facades\Token;

class OilCardController extends Controller
{
    public function index()
    {
        //
    }

    public function store(Request $request)
    {
        $mobile     = trim($request->input('mobile'));
        $smsCode    = $request->input('sms_code');
        $uid = Token::data('id');
        $user = User::find($uid);
        $data = $request->only([
            'card_no',
            'type',
            'name',
            'mobile'
        ]);
        // 验证手机短信码是否正确
//
//        if (!Sms::validation($mobile, $smsCode)) {
//            return fail(400, '验证码错误');
//        }

        $data['mobile'] = $user->mobile;

        $validator = Validator::make($request->all(), [
            'card_no' => 'required|unique:oil_card',
            'type' => 'required',
            'name' => 'required',
            //'mobile' => 'required'
        ]);

        if ($validator->fails()) {
            return fail(400, $validator->errors()->first());
        }

        $data['user_id'] = $uid;
        $card = OilCard::create($data);

        // 如果是第一次绑定油卡，需要赠送相应的优惠券
        /*
        $bindCouponIds = Configure::bindOilCardCoupon();
        $isFirst = (OilCard::where('user_id', $uid)->count() <= 1);
        if ($bindCouponIds && $isFirst) {
            foreach ($bindCouponIds as $couponId) {
                UserCoupon::sendToUser($couponId, $uid);
            }
        }
        // 如果有上级，给上级送优惠券
        if ($user->parent_id && $isFirst) {
            $regCouponIds = Configure::parentRegCoupon();
            if ($regCouponIds) {
                foreach ($regCouponIds as $couponId) {
                    UserCoupon::sendToUser($couponId, $user->parent_id);
                }
            }
        }
        */

        return success($card);
    }

    public function setDefault($id)
    {
        $uid = Token::data('id');
        $cards = OilCard::where('user_id', $uid)->get();
        foreach ($cards as $card) {
            if ($card->id == $id) {
                $card->is_default = 1;
                $card->save();
            } else {
                $card->is_default = 0;
                $card->save();
            }
        }
        return success();
    }

    public function destroy($id)
    {
        $uid = Token::data('id');
        $card = OilCard::where('id', $id)->where('user_id', $uid)->first();
        if ($card) {
            $card->status = 0;
            $card->save();
        }
        return success();
    }
}